package com.ambow.common.web.adive;

import com.ambow.apimodel.common.Response;
import com.ambow.apimodel.common.Status;
import com.ambow.common.web.adive.exception.BizException;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * Created by zhangyl on 2018/6/29
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    public static final Logger logger=LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BizException.class)
    public Response bizExeception(BizException e) {
        Response result=new Response();
        result.setStatus(Status.FAILED);
        if (StringUtils.isNotEmpty(e.getMsg())) {
            result.setMessage(e.getMsg());
        }
        logger.error("业务异常", e.getErrorCode() + ":" + e.getMsg(), e);
        return result;
    }
    @ExceptionHandler(value = RuntimeException.class)
    public Response runtimeException(RuntimeException ex) {
        return exception(ex);
    }
    @ExceptionHandler(value = Exception.class)
    public Response exception(Exception ex) {
        Response result=new Response();
        result.setMessage(ex.getMessage());
        if (ex instanceof UnauthenticatedException) {
            result.setMessage("token错误");
        } else if (ex instanceof UnauthorizedException) {
            result.setMessage("用户无权限");
        } else {
            result.setMessage(ex.getMessage());
        }
        result.setStatus(Status.FAILED);
        logger.error(ex.getMessage(),ex);
        return result;
    }
}
